package cn.satoken.service.impl;

import cn.satoken.entity.AiProperties;
import cn.satoken.service.QwenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <h3>saToken</h3>
 * <p></p>
 *
 * @author gdw
 * @since 2025-06-06 16:43:06
 */
@Service
public class QwenServiceImpl implements QwenService {
    private final RestTemplate restTemplate = new RestTemplate();

    @Autowired
    private AiProperties aiProperties;
    @Override
    public String chatWithQwen(String prompt) {
        HttpHeaders headers = new HttpHeaders();
        headers.setBearerAuth(aiProperties.getApiKey());
        headers.setContentType(MediaType.APPLICATION_JSON);

        // 添加系统提示，定义 AI 的身份
        Map<String, String> systemMessage = new HashMap<>();
        systemMessage.put("role", "system");
        systemMessage.put("content", "你是一个CRM资源管理系统的智能AI助手，可以帮助用户解答系统功能、操作流程等问题。");
        // 构建 messages 列表
        List<Map<String, String>> messages = new ArrayList<>();
        messages.add(systemMessage);
        Map<String, String> userMessage = new HashMap<>();
        userMessage.put("role", "user");
        userMessage.put("content", prompt); // 一定是字符串
        messages.add(userMessage);

        // 构建请求体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("model", aiProperties.getModel()); // 例如 "qwen-plus"
        requestBody.put("messages", messages);

        // 可选参数
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("temperature", 0.7);
        requestBody.put("parameters", parameters);

        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);

        try {
            ResponseEntity<String> response = restTemplate.postForEntity(aiProperties.getApiUrl(), entity, String.class);
            return response.getBody();
        } catch (Exception e) {
            e.printStackTrace();
            return "调用通义失败：" + e.getMessage();
        }
    }
}
